package com.example.ai.service;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 电商服务类，提供商品和订单相关的功能
 */
@Service
public class EcommerceService {
    
    // 模拟商品数据库
    private final Map<String, Product> productDatabase = new HashMap<>();
    
    // 模拟订单数据库
    private final Map<String, Order> orderDatabase = new HashMap<>();
    
    public EcommerceService() {
        // 初始化一些模拟商品数据
        initProducts();
    }
    
    /**
     * 初始化商品数据
     */
    private void initProducts() {
        productDatabase.put("1001", new Product("1001", "智能手机A", "高性能智能手机，配备最新处理器和高清摄像头", 2999.0, "电子产品"));
        productDatabase.put("1002", new Product("1002", "笔记本电脑B", "轻薄便携，适合办公和学习", 4999.0, "电子产品"));
        productDatabase.put("1003", new Product("1003", "无线耳机C", "主动降噪，长续航", 899.0, "配件"));
        productDatabase.put("1004", new Product("1004", "智能手表D", "健康监测，运动追踪", 1299.0, "智能设备"));
        productDatabase.put("1005", new Product("1005", "蓝牙音箱E", "360度环绕音效", 599.0, "音频设备"));
    }
    
    /**
     * 获取所有商品列表
     */
    public List<Product> getAllProducts() {
        return new ArrayList<>(productDatabase.values());
    }
    
    /**
     * 根据ID获取商品详情
     */
    public Product getProductById(String productId) {
        return productDatabase.get(productId);
    }
    
    /**
     * 搜索商品
     */
    public List<Product> searchProducts(String keyword) {
        List<Product> results = new ArrayList<>();
        if (keyword == null || keyword.isEmpty()) {
            return results;
        }
        
        String lowerKeyword = keyword.toLowerCase();
        for (Product product : productDatabase.values()) {
            if (product.getName().toLowerCase().contains(lowerKeyword) || 
                product.getDescription().toLowerCase().contains(lowerKeyword) ||
                product.getCategory().toLowerCase().contains(lowerKeyword)) {
                results.add(product);
            }
        }
        
        return results;
    }
    
    /**
     * 创建订单
     */
    public Order createOrder(String userId, List<String> productIds) {
        Order order = new Order();
        order.setOrderId(generateOrderId());
        order.setUserId(userId);
        order.setStatus("PENDING");
        
        double totalAmount = 0;
        List<OrderItem> items = new ArrayList<>();
        
        for (String productId : productIds) {
            Product product = productDatabase.get(productId);
            if (product != null) {
                OrderItem item = new OrderItem();
                item.setProductId(productId);
                item.setName(product.getName());
                item.setPrice(product.getPrice());
                item.setQuantity(1);
                items.add(item);
                totalAmount += product.getPrice();
            }
        }
        
        order.setItems(items);
        order.setTotalAmount(totalAmount);
        
        // 保存订单
        orderDatabase.put(order.getOrderId(), order);
        
        return order;
    }
    
    /**
     * 生成订单ID
     */
    private String generateOrderId() {
        return "ORD-" + System.currentTimeMillis() + "-" + ThreadLocalRandom.current().nextInt(1000, 9999);
    }
    
    /**
     * 获取订单详情
     */
    public Order getOrderById(String orderId) {
        return orderDatabase.get(orderId);
    }
    
    /**
     * 获取用户的所有订单
     */
    public List<Order> getUserOrders(String userId) {
        List<Order> userOrders = new ArrayList<>();
        for (Order order : orderDatabase.values()) {
            if (order.getUserId().equals(userId)) {
                userOrders.add(order);
            }
        }
        return userOrders;
    }
    
    /**
     * 商品类
     */
    public static class Product {
        private String id;
        private String name;
        private String description;
        private double price;
        private String category;
        
        public Product() {}
        
        public Product(String id, String name, String description, double price, String category) {
            this.id = id;
            this.name = name;
            this.description = description;
            this.price = price;
            this.category = category;
        }
        
        // Getters and Setters
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        public double getPrice() { return price; }
        public void setPrice(double price) { this.price = price; }
        public String getCategory() { return category; }
        public void setCategory(String category) { this.category = category; }
    }
    
    /**
     * 订单类
     */
    public static class Order {
        private String orderId;
        private String userId;
        private String status;
        private double totalAmount;
        private List<OrderItem> items = new ArrayList<>();
        
        // Getters and Setters
        public String getOrderId() { return orderId; }
        public void setOrderId(String orderId) { this.orderId = orderId; }
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        public double getTotalAmount() { return totalAmount; }
        public void setTotalAmount(double totalAmount) { this.totalAmount = totalAmount; }
        public List<OrderItem> getItems() { return items; }
        public void setItems(List<OrderItem> items) { this.items = items; }
    }
    
    /**
     * 订单项类
     */
    public static class OrderItem {
        private String productId;
        private String name;
        private double price;
        private int quantity;
        
        // Getters and Setters
        public String getProductId() { return productId; }
        public void setProductId(String productId) { this.productId = productId; }
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public double getPrice() { return price; }
        public void setPrice(double price) { this.price = price; }
        public int getQuantity() { return quantity; }
        public void setQuantity(int quantity) { this.quantity = quantity; }
    }
}